package com.medical.app.controller;

import com.medical.app.dto.request.MedicalRecordRequest;
import com.medical.app.dto.response.ApiResponse;
import com.medical.app.entity.MedicalRecord;
import com.medical.app.entity.User;
import com.medical.app.service.MedicalRecordService;
import com.medical.app.service.UserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;

import java.util.List;
import java.util.Optional;

@RestController
@RequestMapping("/api/medical-records")
@CrossOrigin(origins = "*")
public class MedicalRecordController {

    @Autowired
    private MedicalRecordService medicalRecordService;

    @Autowired
    private UserService userService;

    // 获取用户病例记录
    @GetMapping("/user/{userId}")
    public ResponseEntity<ApiResponse<List<MedicalRecord>>> getUserRecords(@PathVariable Long userId) {
        try {
            if (!userService.findById(userId).isPresent()) {
                return ResponseEntity.badRequest().body(ApiResponse.error("用户不存在"));
            }
            List<MedicalRecord> records = medicalRecordService.getUserRecords(userId);
            return ResponseEntity.ok(ApiResponse.success(records));
        } catch (Exception e) {
            return ResponseEntity.badRequest().body(ApiResponse.error(e.getMessage()));
        }
    }

    // 创建病例记录
    @PostMapping
    public ResponseEntity<ApiResponse<MedicalRecord>> createRecord(@RequestBody MedicalRecordRequest request) {
        try {
            Optional<User> user = userService.findById(request.getUserId());
            if (!user.isPresent()) {
                return ResponseEntity.badRequest().body(ApiResponse.error("用户不存在"));
            }

            MedicalRecord record = new MedicalRecord();
            record.setDate(request.getDate());
            record.setHospital(request.getHospital());
            record.setDepartment(request.getDepartment());
            record.setDoctor(request.getDoctor());
            record.setDiagnosis(request.getDiagnosis());
            record.setSymptoms(request.getSymptoms());
            record.setPrescription(request.getPrescription());
            record.setImageUrls(request.getImageUrls());
            record.setUser(user.get());

            MedicalRecord savedRecord = medicalRecordService.saveRecord(record);
            return ResponseEntity.ok(ApiResponse.success("创建成功", savedRecord));
        } catch (Exception e) {
            return ResponseEntity.badRequest().body(ApiResponse.error(e.getMessage()));
        }
    }

    // 更新病例记录 - 新增接口
    @PutMapping("/{id}")
    public ResponseEntity<ApiResponse<MedicalRecord>> updateRecord(
            @PathVariable Long id,
            @RequestBody MedicalRecordRequest request) {
        try {
            Optional<MedicalRecord> existingRecord = medicalRecordService.findById(id);
            if (!existingRecord.isPresent()) {
                return ResponseEntity.badRequest().body(ApiResponse.error("病例记录不存在"));
            }

            // 验证用户权限（确保用户只能修改自己的记录）
            MedicalRecord record = existingRecord.get();
            if (!record.getUser().getId().equals(request.getUserId())) {
                return ResponseEntity.badRequest().body(ApiResponse.error("无权修改此记录"));
            }

            // 创建更新对象
            MedicalRecord recordToUpdate = new MedicalRecord();
            recordToUpdate.setDate(request.getDate());
            recordToUpdate.setHospital(request.getHospital());
            recordToUpdate.setDepartment(request.getDepartment());
            recordToUpdate.setDoctor(request.getDoctor());
            recordToUpdate.setDiagnosis(request.getDiagnosis());
            recordToUpdate.setSymptoms(request.getSymptoms());
            recordToUpdate.setPrescription(request.getPrescription());
            recordToUpdate.setImageUrls(request.getImageUrls());

            MedicalRecord updatedRecord = medicalRecordService.updateRecord(id, recordToUpdate);
            return ResponseEntity.ok(ApiResponse.success("更新成功", updatedRecord));
        } catch (Exception e) {
            return ResponseEntity.badRequest().body(ApiResponse.error(e.getMessage()));
        }
    }

    // 删除病例记录
    @DeleteMapping("/{id}")
    public ResponseEntity<ApiResponse<String>> deleteRecord(@PathVariable Long id) {
        try {
            medicalRecordService.deleteRecord(id);
            return ResponseEntity.ok(ApiResponse.success("删除成功"));
        } catch (Exception e) {
            return ResponseEntity.badRequest().body(ApiResponse.error(e.getMessage()));
        }
    }

    // 获取单个病例记录详情
    @GetMapping("/{id}")
    public ResponseEntity<ApiResponse<MedicalRecord>> getRecordById(@PathVariable Long id) {
        try {
            Optional<MedicalRecord> record = medicalRecordService.findById(id);
            if (record.isPresent()) {
                return ResponseEntity.ok(ApiResponse.success(record.get()));
            } else {
                return ResponseEntity.badRequest().body(ApiResponse.error("病例记录不存在"));
            }
        } catch (Exception e) {
            return ResponseEntity.badRequest().body(ApiResponse.error(e.getMessage()));
        }
    }
}